package com.ble.testpost.http;

import com.ble.testpost.BuildConfig;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by lch on 2018/2/10 0010.
 */

public class AppHttpClient {

    private static AppApi appApi;

    private static Retrofit retrofit;

    private static Retrofit getRetrofit(String baseUrl) {

        if (retrofit == null) {

            final OkHttpClient.Builder builder = new OkHttpClient.Builder();

            Interceptor parameterInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    //公共参数
                    HttpUrl httpUrl = chain.request().url().newBuilder()
                            .addQueryParameter("platform", "android")
                            .build();
                    Request.Builder requestBuilder = chain.request().newBuilder()
                            .url(httpUrl);
                    return chain.proceed(requestBuilder.build());
                }
            };

            builder.addInterceptor(parameterInterceptor);


            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(loggingInterceptor);
            }

            builder.connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true);

            OkHttpClient client = builder.build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
        }

        return retrofit;
    }

    public static AppApi ApiService() {
        if (appApi == null) {
            appApi = getRetrofit(AppUrl.BASE_URL).create(AppApi.class);
        }
        return appApi;
    }
}
